package cn.wolfcode.crm.util;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.SystemMenu;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.Iterator;
import java.util.List;

/**
 * @program: crm
 * @description:
 * @author: Mr.chen
 * @create: 2018-07-14 18:27
 **/
public class SystemMenuUtil {
    public static final String SYSTEM_MENU_IN_SESSION = "system_menu_in_session" ;

    /**
     * 过滤没有权限菜单
     */
    public static void filterPermissionMenu(List<SystemMenu> menus){
        //获取当前登录对象
        Subject subject = SecurityUtils.getSubject();
        //遍历菜单集合, 检查菜单是否需要进行权限控制
        Iterator<SystemMenu> iterator = menus.iterator();
        while(iterator.hasNext()){
            SystemMenu menu = iterator.next();
            //permission为null表示不需要权限检查
            Permission permission = menu.getPermission();
            if (permission != null){
                //才执行权限操作
                //如果需要控制, 而当前用户又没有权限, 则删除
                if(!subject.isPermitted(permission.getResource())){
                    iterator.remove();
                }
            }
            //紫菜单也需要做权限查询
            if (menu.getChildren()!=null && menu.getChildren().size()>0){
                filterPermissionMenu(menu.getChildren());
            }
        }
    }
    /*
    过滤没有权限的菜单
     */

    public static void filterMenu(List<SystemMenu> menus){
        filterPermissionMenu(menus);
        //过滤掉空父节点
        Iterator<SystemMenu> iterator = menus.iterator();
        while(iterator.hasNext()){
            SystemMenu menu = iterator.next();
            if (menu.getChildren()==null || menu.getChildren().size()==0){
                iterator.remove();
            }
        }
    }

}
